<?php
class InsertController extends AppController {
	
	public $names = "InsertController";
	public $uses = array("MongoArticle", "MetadataFields", "Author", "Journal", "Issue");
	
	public function index() {
		$this->log("---- InsertController -> index ----");
		
		$journalList = $this->Journal->getAlls();
		$issueList = $this->Issue->getAlls();
		$authorList = $this->Author->getAlls();
		
		$this->set(compact("issueList", "journalList", "authorList"));
		
		$this->log($this->MongoArticle->openConnection());
	}
	
	public function insertArticle() {
		$data = $this->request->data;
		$decodedData = $this->decodeJson($data);
		$result['message'] = $this->MongoArticle->insert('article', $decodedData);
		$result['status'] = true;
		
		$this->ajaxResponse(json_encode($result, JSON_UNESCAPED_UNICODE));
	}
	
	private function decodeJson($data) {
		$decodeFields = $this->MetadataFields->getDecodeFields();
		$decodeFieldsArray = $this->MetadataFields->getDecodeFieldsArray();
		
		$result = array();
		foreach ($data as $key => $value) {
			if (in_array($key, $decodeFields)) {
				$result[$key] = json_decode(base64_decode($value));
			} elseif (in_array($key, $decodeFieldsArray)) {
				$tempArray = array();
				foreach ($value as $v) {
					if ($v != "") {
						$tempArray[] = json_decode(base64_decode($v));
					}
				}
				$result[$key] = $tempArray;
			} else {
				$result[$key] = $value;
			}
		}
		return $result;
	}
}
?>